import React, { useEffect, useState, Fragment } from 'react';
import { connect } from 'umi';
import { Form, Card, Button, Table } from 'antd';
import { history } from 'umi';
import moment from 'moment';
import { eventTrack } from '@/utils/track';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import LinkTo from '@/components/LinkTo';
import AuthComponent from '@/utils/auth/AuthComponent';
import AuthCode from '@/utils/auth/AuthCode';
import authHelper from '@/utils/auth/helper';
import { withRoutePage } from '@/utils/enhanceUtils';
import PageRouter from '@/components/PageRouter/PageRouter';
import Pagination from '@/components/Pagination';
import SearchForm from './Components/SearchForm';
import styles from './TalentPoolList.less';

const { checkCode } = authHelper;

const MyTalentPool = ({ dispatch, form, talentPool, user, location, loading, ...args }) => {
    const { query } = location;

    // 按钮权限控制
    const { authCode } = new AuthCode(args.route.code);
    const { pagination, myTalentPoolList, orderBy } = talentPool;
    const User = user.currentUser; // 登陆人信息
    const candidateAgreeType = talentPool.candidateAgreeTypeList; // 学历类型
    const candidateSexType = talentPool.candidateSexTypeList; // 性别类型
    const [sorterInfo, setSorterInfo] = useState(); // 排序储存
    let identity = ''; // 访问页面人的身份信息
    // 获取路由上的name值进行判断身份
    if (args && args.route.name === 'adminTalentPool') {
        identity = 'admin';
    } else {
        identity = 'user';
    }

    const autoLinkTo = list => {
        if (checkCode(authCode('detail'))) {
            return (
                <LinkTo
                    className={styles.LinkTo}
                    to="/office/personnelManagement/recruit/talentPool/detail"
                    query={{
                        code: list.talentCode,
                        companyId: '101'
                    }}
                >
                    {list.talentName}
                </LinkTo>
            );
        }
        return list.talentName;
    };
    const getSexName = key => {
        if (key === '1') {
            return (
                <i className="iconfont iconoa_table_icon_men_default" style={{ color: '#3aa0ff', margin: '0 5px' }} />
            );
        }
        if (key === '2') {
            return (
                <i className="iconfont iconoa_table_icon_women_default" style={{ color: '#f2637b', margin: '0 5px' }} />
            );
        }
        return '';
    };
    const getName = list => (
        <Fragment>
            <div className={styles.colum_info_1}>
                <div
                    title={list.talentName}
                    style={{
                        display: 'inline-block',
                        maxWidth: '200px',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        whiteSpace: 'nowrap',
                        verticalAlign: ' text-bottom'
                    }}
                >
                    {identity === 'admin' ? (
                        autoLinkTo(list)
                    ) : (
                        <LinkTo
                            onClick={async (e, url) => {
                                await eventTrack({
                                    eventName: 'personal_my_recruit_talentPool_detail_click',
                                    eventProps: {
                                        label: '我的人才库-人才详情'
                                    }
                                });
                                history.push(url);
                            }}
                            className={styles.LinkTo}
                            to="/personal/portal/recruit/talentPool/detail"
                            query={{
                                code: list.talentCode,
                                companyId: '101'
                            }}
                        >
                            {list.talentName}
                        </LinkTo>
                    )}
                </div>
                {getSexName(list.talentSex)}
                {list.age ? `${list.age} 岁 ` : ''}
            </div>
            <div className={styles.colum_info_2}>
                {list.lastCompany}
                {list.lastPost ? ` | ${list.lastPost}` : ''}
            </div>
            <div className={styles.colum_info_2}>
                {list.talentGraduateSchool ? `${list.talentGraduateSchool} | ` : ''}
                {list.talentProfessional ? `${list.talentProfessional}  | ` : ''}
                {list.talentDegreeValue}
            </div>
        </Fragment>
    );
    const columns = [
        {
            title: '姓名',
            dataIndex: 'talentName',
            key: 'talentName',
            width: 160,
            fixed: 'left',
            render: (text, record) => getName(record)
        },
        {
            title: '应聘职位',
            dataIndex: 'recruitPosts',
            key: 'recruitPosts',
            width: 200,
            fixed: 'left',
            render: (text, record) => record.recruitPosts.map(item => <div>{item}</div>)
        },
        {
            title: '入库时间',
            dataIndex: 'insertDate',
            key: 'insertDate',
            sorter: () => {},
            width: 200,
            className: styles.row120
        },
        {
            title: '经验/工龄',
            dataIndex: 'workAge',
            key: 'workAge',
            sorter: () => {},
            width: 120,
            className: styles.row120
        },
        {
            title: '邮箱',
            dataIndex: 'talentEmail',
            key: 'talentEmail',
            width: 120,
            className: styles.row120,
            render: text => (
                <div
                    style={{
                        display: 'inline-block',
                        maxWidth: '200px',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        whiteSpace: 'nowrap',
                        verticalAlign: ' text-bottom'
                    }}
                    title={text}
                >
                    {text}
                </div>
            )
        },
        {
            title: '手机',
            dataIndex: 'talentPhone',
            key: 'talentPhone',
            width: 160,
            className: styles.row120
        },
        {
            title: '简历管理人',
            dataIndex: 'talentLeaderName',
            key: 'talentLeaderName',
            // width: 140,
            className: styles.row120
        },
        {
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            render: (text, record) => (
                <LinkTo
                    onClick={async (e, url) => {
                        await eventTrack({
                            eventName: 'personnel_management_recruit_talentPool_operator_click',
                            eventProps: {
                                label: '人才管理-操作-编辑'
                            }
                        });
                        history.push(url);
                    }}
                    to={
                        identity === 'admin'
                            ? '/office/personnelManagement/recruit/talentPool/detail'
                            : '/personal/portal/recruit/talentPool/detail'
                    }
                    disabled={identity === 'admin' ? !checkCode(authCode('edit')) : !record.isEdit}
                    query={{
                        code: record.talentCode,
                        companyId: '101'
                    }}
                >
                    编辑
                </LinkTo>
            ),
            width: 100,
            fixed: 'right'
        }
    ];
    // 获取性别和学历的数据字典
    const getDict = () => {
        dispatch({
            type: 'talentPool/getDict'
        });
    };
    const getPayload = type => {
        const {
            insertDate,
            searchName,
            talentEmail,
            talentLeaderId,
            talentPhone,
            lastPost,
            talentSex,
            talentDegree
        } = form.getFieldsValue();
        const payload = {
            searchName: searchName || '',
            talentPhone: talentPhone || '',
            talentEmail: talentEmail || '',
            beginTime: insertDate && insertDate.length > 0 ? moment(insertDate[0]).format('YYYY-MM-DD 00:00:00') : '',
            endTime: insertDate && insertDate.length > 0 ? moment(insertDate[1]).format('YYYY-MM-DD 23:59:59') : '',
            talentLeaderId: talentLeaderId || '',
            lastPost: lastPost || '',
            talentSex: talentSex || '',
            talentDegree: talentDegree || '',
            orderByField: orderBy,
            pageNo: type ? 1 : pagination.current,
            pageSize: type ? 10 : pagination.pageSize
        };
        return payload;
    };

    // 高级搜索
    const handleSearch = type => {
        // 后端接口问题，人才库列表需要拆成两个，分HR使用和管理员使用，目前根据路由name判断身份
        dispatch({
            type: identity === 'admin' ? 'talentPool/getalltalentsAdmin' : 'talentPool/getalltalents',
            payload: getPayload(type)
        });
    };

    // 表格表头点击切换排序
    const changeTable = (paginations, filters, sorter) => {
        const extra = {};
        if (sorterInfo !== sorter) {
            extra.current = 1;
            setSorterInfo(sorter);
        }
        let orderBys;
        let sorterField;
        if (sorter && sorter.field && sorter.order) {
            if (sorter.field === 'insertDate') {
                sorterField = 'insert_date';
            }
            if (sorter.field === 'workAge') {
                sorterField = 'talent_graduate';
            }
            const order = sorter.order.trim().split('end')[0];
            orderBys = `${sorterField} ${order}`;
        }
        dispatch({
            type: 'talentPool/save',
            payload: {
                orderBy: orderBys || '',
                pagination: {
                    ...talentPool.pagination,
                    ...paginations,
                    ...extra
                }
            }
        });
    };

    // 组件卸载时候 清空表单请求参数（高级搜索内容、分页、排序字段）
    useEffect(
        () => () => {
            dispatch({
                type: 'talentPool/save',
                payload: {
                    orderBy: '',
                    pagination: {
                        ...pagination,
                        pageSize: 10,
                        current: 1
                    }
                }
            });
        },
        []
    );

    // 初始化查询参数，用于 URL 参数化
    const initFields = React.useCallback(() => {
        const { beginTime, endTime } = query;
        form.setFieldsValue({
            insertDate: beginTime ? [moment(beginTime), moment(endTime)] : '',
            searchName: query.searchName || '',
            talentPhone: query.talentPhone || '',
            talentEmail: query.talentEmail || '',
            talentLeaderId: query.talentLeaderId ? Number(query.talentLeaderId) : undefined,
            lastPost: query.lastPost || '',
            talentSex: query.talentSex || '',
            talentDegree: query.talentDegree || undefined
        });
    }, [form]);

    useEffect(() => {
        initFields();
        getDict();
    }, []);

    useEffect(() => {
        handleSearch();
    }, [pagination.pageSize, pagination.current, orderBy]);

    const extraButton =
        identity === 'admin' ? (
            <AuthComponent code={authCode('add')}>
                <Button
                    type="primary"
                    onClick={async () => {
                        await eventTrack({
                            eventName: 'personnel_management_recruit_talentPool_add_click',
                            eventProps: {
                                label: '人才管理-添加人才简历'
                            }
                        });
                        history.push({
                            pathname: '/office/personnelManagement/recruit/talentPool/add'
                        });
                    }}
                >
                    {/* : '/personal/recruit/talentPool/add' */}
                    添加人才简历
                </Button>
            </AuthComponent>
        ) : (
            <Button
                type="primary"
                onClick={async () => {
                    // 埋点
                    await eventTrack({
                        eventName: 'personal_my_recruit_talentPool_add_click',
                        eventProps: { label: '我的人才库-添加人才简历' }
                    });
                    history.push({
                        pathname: '/personal/portal/recruit/talentPool/add'
                    });
                }}
            >
                添加人才简历
            </Button>
        );

    return (
        <PageHeaderWrapper>
            <PageRouter type="myrecruit" extraButton={extraButton}>
                {isPageRouter => (
                    <Card
                        bordered={false}
                        title={isPageRouter ? null : '人才管理'}
                        extra={isPageRouter ? null : extraButton}
                    >
                        <SearchForm
                            user={User}
                            form={form}
                            candidateAgreeType={candidateAgreeType}
                            candidateSexType={candidateSexType}
                            onSearch={e => {
                                const { eType } = e;
                                history.push({
                                    query: {
                                        ...query,
                                        ...getPayload(1)
                                    }
                                });
                                // 埋点
                                eventTrack({
                                    eventName:
                                        eType === 'submit'
                                            ? 'personal_my_recruit_talentPool_search_click'
                                            : 'personnel_management_recruit_talentPool_reset_click',
                                    eventProps: {
                                        label: eType === 'submit' ? '我的人才库-搜索' : '我的人才库-清空',
                                        key_words: eType === 'submit' ? JSON.stringify(form.getFieldsValue()) : null
                                    }
                                });
                                handleSearch(1);
                            }}
                        />
                        <Table
                            loading={loading}
                            dataSource={myTalentPoolList}
                            columns={columns}
                            scroll={{ x: 'max-content' }}
                            onChange={changeTable}
                            rowKey="id"
                            pagination={false}
                        />
                        <Pagination {...pagination} onChange={changeTable} sorter={sorterInfo} loading={loading} />
                    </Card>
                )}
            </PageRouter>
        </PageHeaderWrapper>
    );
};
export default withRoutePage(
    connect(({ loading, talentPool, user }) => ({
        talentPool,
        user,
        loading: loading.models.talentPool
    }))(Form.create()(MyTalentPool))
);
